import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Contact, ContactCategory, ContactStatus } from './type'
import { Users, User } from 'lucide-vue-next'

export const useContactStore = defineStore('contact', () => {
  // 联系人列表
  const contacts = ref<Contact[]>([])

  // 搜索关键词
  const searchQuery = ref('')

  // 当前选中的分类
  const activeCategory = ref('all')

  // 当前选中的联系人ID
  const selectedContactId = ref('')

  // 加载状态
  const isLoading = ref(false)

  // 联系人分类配置
  const contactCategories = computed<ContactCategory[]>(() => [
    {
      type: 'all',
      name: '全部',
      icon: Users,
      count: contacts.value.length
    },
    {
      type: 'friend',
      name: '好友',
      icon: User,
      count: contacts.value.filter((c) => c.type === 'friend').length
    },
    {
      type: 'group',
      name: '群组',
      icon: Users,
      count: contacts.value.filter((c) => c.type === 'group').length
    }
  ])

  // 过滤后的联系人列表
  const filteredContacts = computed(() => {
    let result = contacts.value

    // 按分类筛选
    if (activeCategory.value !== 'all') {
      result = result.filter((contact) => contact.type === activeCategory.value)
    }

    // 按搜索关键词筛选
    if (searchQuery.value.trim()) {
      const query = searchQuery.value.toLowerCase().trim()
      result = result.filter(
        (contact) =>
          contact.name.toLowerCase().includes(query) ||
          (contact.lastMessage && contact.lastMessage.toLowerCase().includes(query))
      )
    }

    return result
  })

  // 在线联系人数量
  const onlineContactsCount = computed(
    () => contacts.value.filter((c) => c.status === 'online').length
  )

  // 好友数量
  const friendsCount = computed(() => contacts.value.filter((c) => c.type === 'friend').length)

  // 群组数量
  const groupsCount = computed(() => contacts.value.filter((c) => c.type === 'group').length)

  // ========== 操作方法 ==========

  // 设置搜索关键词
  const setSearchQuery = (query: string): void => {
    searchQuery.value = query
  }

  // 设置活跃分类
  const setActiveCategory = (category: string): void => {
    activeCategory.value = category
  }

  // 选择联系人
  const selectContact = (contactId: string): void => {
    selectedContactId.value = contactId
  }

  // 根据ID获取联系人
  const getContactById = (id: string): Contact | undefined => {
    return contacts.value.find((contact) => contact.id === id)
  }

  // 添加联系人
  const addContact = (contact: Contact): void => {
    const existingIndex = contacts.value.findIndex((c) => c.id === contact.id)
    if (existingIndex === -1) {
      contacts.value.push(contact)
    } else {
      // 如果已存在，则更新
      contacts.value[existingIndex] = contact
    }
  }

  // 删除联系人
  const removeContact = (contactId: string): void => {
    const index = contacts.value.findIndex((c) => c.id === contactId)
    if (index !== -1) {
      contacts.value.splice(index, 1)
    }
    // 如果删除的是当前选中的联系人，清除选中状态
    if (selectedContactId.value === contactId) {
      selectedContactId.value = ''
    }
  }

  // 更新联系人信息
  const updateContact = (contactId: string, updates: Partial<Contact>): void => {
    const index = contacts.value.findIndex((c) => c.id === contactId)
    if (index !== -1) {
      contacts.value[index] = { ...contacts.value[index], ...updates }
    }
  }

  // 更新联系人状态
  const updateContactStatus = (contactId: string, status: ContactStatus): void => {
    updateContact(contactId, { status })
  }

  // 更新联系人最后消息
  const updateContactLastMessage = (contactId: string, message: string): void => {
    updateContact(contactId, { lastMessage: message })
  }

  // 批量更新联系人
  const setContacts = (newContacts: Contact[]): void => {
    contacts.value = newContacts
  }

  // 清空所有联系人
  const clearContacts = (): void => {
    contacts.value = []
    selectedContactId.value = ''
  }

  // 设置加载状态
  const setLoading = (loading: boolean): void => {
    isLoading.value = loading
  }

  // ========== 业务逻辑方法 ==========

  // 初始化模拟数据 - 现在只是一个空壳，实际数据由mock/examples.ts提供
  const initMockData = async (): Promise<void> => {
    console.log('联系人使用自定义mock数据进行初始化')
    try {
      // 导入自定义mock数据
      const { initializeWithMockData } = await import('@/mock/examples')
      await initializeWithMockData()
    } catch (error) {
      console.error('加载自定义联系人mock数据失败:', error)
    }
  }

  // 搜索联系人
  const searchContacts = async (query: string): Promise<void> => {
    setLoading(true)
    setSearchQuery(query)

    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 300))

    setLoading(false)
  }

  // 添加好友
  const addFriend = async (friendData: Omit<Contact, 'id'>): Promise<void> => {
    setLoading(true)

    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      const newFriend: Contact = {
        id: Date.now().toString(),
        ...friendData,
        type: 'friend'
      }

      addContact(newFriend)
    } finally {
      setLoading(false)
    }
  }

  // 创建群组
  const createGroup = async (groupData: Omit<Contact, 'id'>): Promise<void> => {
    setLoading(true)

    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      const newGroup: Contact = {
        id: Date.now().toString(),
        ...groupData,
        type: 'group'
      }

      addContact(newGroup)
    } finally {
      setLoading(false)
    }
  }

  return {
    contacts,
    searchQuery,
    activeCategory,
    selectedContactId,
    isLoading,

    // 计算属性
    contactCategories,
    filteredContacts,
    onlineContactsCount,
    friendsCount,
    groupsCount,

    // 基础操作
    setSearchQuery,
    setActiveCategory,
    selectContact,
    getContactById,
    addContact,
    removeContact,
    updateContact,
    updateContactStatus,
    updateContactLastMessage,
    setContacts,
    clearContacts,
    setLoading,

    // 业务操作
    initMockData,
    searchContacts,
    addFriend,
    createGroup
  }
})
